package org.filesort;

import java.io.*;

/**
 * This is the entity, which customize IFileSorter to work with specific
 * records in file. It takes responsibility of serializing/deserializing
 * records to/from binary representation, and sort them efficiently
 *
 * @author cheremin
 * @since 10.02.12,  15:49
 */
public interface IFileContentProcessor {

    /** @return size of record, in bytes. Chunks/runs will be aligned with it. */
    public int dataElementSize();

    /**
     * Method reads runLength bytes from source (runLength%dataElementSize() == 0),
     * deserializes records, sort them, and serializes sorted records into target
     */
    public void sortRun( final IBytesSource source,
                         final IBytesTarget target,
                         final int runLength ) throws IOException;

    /**
     * Method reads up to maxRunLength bytes from each of sources, deserializes
     * records, and serializes them sorted into target
     * <p/>
     * Each of sources guaranteed to contains integer records before exhausted.
     * <p/>
     * maxRunLength is not guaranteed to reached -- it is just the top approximation. All sources
     * must be read up until exhausted (IBytesSource.get() returns 0)
     */
    public void merge( final IBytesSource[] sources,
                       final long maxRunLength,
                       final IBytesTarget target ) throws IOException;

    interface IBytesTarget {
        /** Puts length bytes from buffer into stream */
        public void put( final byte[] buffer,
                         final int length ) throws IOException;
    }

    interface IBytesSource {
        /**
         * Fills buffer with data, returning actual number of bytes read.
         *
         * @return number of bytes in buffer, which was actually read. 0 or
         * any value &lt; buffer.length means "end-of-source reached"
         */
        public int get( final byte[] buffer ) throws IOException;
    }
}
